Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add fungible keeper ability to lock/unlock ZRC20 tokens #2979

Merged
merged 11 commits into from
Oct 17, 2024

Conversation

fbac
Copy link
Contributor

@fbac fbac commented Oct 7, 2024

Description

Add capabilities to fungible keeper:

  • Fungible Call ZRC20 method.
  • Lock ZRC20.
  • Unlock ZRC20.
  • Check ZRC20 allowance.
  • Check ZRC20 balance.
  • Check ZRC20 validity.
  • Bank contract uses fungible keeper to lock/unlock.

How Has This Been Tested?

  • Tested CCTX in localnet
  • Tested in development environment
  • Go unit tests
  • Go integration tests
  • Tested via GitHub Actions

Summary by CodeRabbit

Release Notes

  • New Features

    • Support for stateful precompiled contracts and staking precompiled contract.
    • Enhanced Bitcoin chain support, including TSS address derivation by chain ID.
    • Introduction of a fungible keeper for locking/unlocking ZRC20 tokens.
    • Integration of authenticated calls into the protocol.
  • Bug Fixes

    • Resolved issues with operator voting on discarded keygen ballots and improved outbound tracking for EVM chains.
  • Tests

    • Expanded testing coverage for stateful precompiled contracts and staking functionalities.
  • Documentation

    • Updated changelog to reflect new features, fixes, and improvements.

These updates significantly enhance functionality, testing coverage, and overall user experience.

Copy link
Contributor

coderabbitai bot commented Oct 7, 2024

📝 Walkthrough

Walkthrough

The pull request introduces significant updates to the Zeta Chain node, encompassing new features, refactoring, testing enhancements, and fixes. Key additions include support for stateful precompiled contracts, a common zetacored RPC package, and improvements to Bitcoin chain integration. The deposit and withdrawal mechanisms for ZRC20 tokens have been streamlined, while new methods for checking allowances and balances have been added. The changelog has been updated to reflect these changes, alongside improvements in the CI pipeline.

Changes

File Path Change Summary
changelog.md Updated to reflect new features, refactors, tests, fixes, and CI improvements, including support for stateful precompiled contracts and enhancements to Bitcoin chain support.
e2e/e2etests/test_precompiles_bank.go Updated bank contract address references from bank.ContractAddress to fungibletypes.ModuleAddressZEVM.
e2e/e2etests/test_precompiles_bank_through_contract.go Changed bank contract address references to fungibletypes.ModuleAddressZEVM for consistency.
precompiles/bank/method_deposit.go Removed validity and allowance checks for ZRC20 tokens in the deposit process, simplifying the logic.
precompiles/bank/method_test.go Updated caller address to fungibletypes.ModuleAddressZEVM and added a test case for zero token deposits.
precompiles/bank/method_withdraw.go Simplified withdrawal logic by consolidating checks for ZRC20 validity and balance.
x/fungible/keeper/zrc20_check_allowance.go Introduced CheckFungibleZRC20Allowance method to verify token allowance for a specified address.
x/fungible/keeper/zrc20_check_balance.go Introduced CheckFungibleZRC20Balance method to verify token balance for a specified address.
x/fungible/keeper/zrc20_check_token_validity.go Added IsValidZRC20 method to validate ZRC20 token addresses.
x/fungible/keeper/zrc20_lock_token.go Introduced LockZRC20 method for locking ZRC20 tokens in a bank contract.
x/fungible/keeper/zrc20_unlock_token.go Introduced UnlockZRC20 method for unlocking and transferring ZRC20 tokens.
x/fungible/types/keys.go Added ModuleAddressZEVM, updated formatting of ModuleAddress, clarified comments, and removed the init function.

Possibly related PRs

Suggested labels

breaking:cli, ADMIN_TESTS, UPGRADE_TESTS

Suggested reviewers

  • kingpinXD
  • swift1337
  • skosito
  • brewmaster012
  • lumtis
  • ws4charlie

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@fbac fbac force-pushed the feat/add-lock-zrc20-function-fungible branch 4 times, most recently from e8f182c to d5190a5 Compare October 8, 2024 10:45
@fbac fbac changed the title feat: add lockZRC20 capability to fungible keeper feat: add fungible keeper ability to lock/unlock ZRC20 tokens Oct 8, 2024
@fbac fbac marked this pull request as ready for review October 8, 2024 11:25
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 23

🧹 Outside diff range and nitpick comments (17)
x/fungible/types/keys.go (2)

32-34: New ModuleAddressZEVM variable approved with a suggestion.

The addition of ModuleAddressZEVM enhances code clarity for zEVM-specific operations. The implementation is consistent with ModuleAddressEVM, promoting code uniformity.

To further improve clarity, consider modifying the comment as follows:

- // ModuleAddressZEVM is calculated in the same way as ModuleAddressEVM.
- // Maintain it for legibility in functions calling fungible module address from zEVM.
+ // ModuleAddressZEVM represents the fungible module's address in zEVM context.
+ // It is calculated identically to ModuleAddressEVM but maintained separately for clarity.

This adjustment succinctly conveys both the purpose and the rationale for the separate variable.


35-35: Formatting adjustment approved with a suggestion for improvement.

The reformatting of the AdminAddress declaration aligns with Go's standard formatting practices, enhancing code consistency and readability.

However, the use of a hardcoded address may present maintenance challenges in the future. Consider the following improvement:

  1. Define the admin address in a configuration file or environment variable.
  2. Implement a function to retrieve the admin address, allowing for easier updates and potential runtime configuration.

Example implementation:

var AdminAddress string

func GetAdminAddress() string {
    if AdminAddress == "" {
        // Load from config or env
        AdminAddress = loadAdminAddressFromConfig()
    }
    return AdminAddress
}

This approach would enhance flexibility and maintainability while preserving the current functionality.

e2e/e2etests/test_precompiles_bank_through_contract.go (2)

63-63: Balance check modification is correct.

The update to use fungibletypes.ModuleAddressZEVM aligns with the new approach for the bank precompile. For consistency, consider extracting this address into a constant at the package level, as it's used multiple times throughout the test.

const bankModuleAddress = fungibletypes.ModuleAddressZEVM

Then use bankModuleAddress in place of fungibletypes.ModuleAddressZEVM throughout the test.


85-85: Balance check modifications are consistent and appropriate.

The updates to use fungibletypes.ModuleAddressZEVM for balance checks are correct and maintain consistency throughout the test. To improve readability and reduce repetition, consider creating a helper function for these balance checks.

func checkBankModuleBalance(r *runner.E2ERunner, expectedBalance int64) {
    balanceShouldBe(r, expectedBalance, checkZRC20Balance(r, fungibletypes.ModuleAddressZEVM))
}

Then use this helper function in place of the repeated balance checks for the bank module address.

Also applies to: 98-98, 107-107, 123-123, 132-132

e2e/e2etests/test_precompiles_bank.go (4)

33-33: Approval address update is correct.

The change to use fungibletypes.ModuleAddressZEVM is appropriate and consistent with the module's new addressing scheme.

Consider adding a comment explaining the significance of this address change for future maintainers:

// Use ModuleAddressZEVM as the new bank contract address for approvals
tx, err := r.ERC20ZRC20.Approve(r.ZEVMAuth, fungibletypes.ModuleAddressZEVM, big.NewInt(0))

107-107: Balance checks updated correctly to use the new module address.

The changes to use fungibletypes.ModuleAddressZEVM in the BalanceOf calls are appropriate and consistent with the new addressing scheme.

To reduce code duplication and improve maintainability, consider refactoring these balance checks into a helper function:

func checkBankZRC20Balance(r *runner.E2ERunner, expectedBalance uint64) error {
    bankZRC20Balance, err := r.ERC20ZRC20.BalanceOf(&bind.CallOpts{Context: r.Ctx}, fungibletypes.ModuleAddressZEVM)
    if err != nil {
        return fmt.Errorf("Call ERC20ZRC20.BalanceOf: %w", err)
    }
    if bankZRC20Balance.Uint64() != expectedBalance {
        return fmt.Errorf("bank ERC20ZRC20 balance should be %d, got %d", expectedBalance, bankZRC20Balance.Uint64())
    }
    return nil
}

Then use it in the test:

require.NoError(r, checkBankZRC20Balance(r, 500), "Bank ERC20ZRC20 balance check failed")

Also applies to: 119-119, 147-147


162-162: Bank address update in non-ZRC20 test is correct.

The change to use fungibletypes.ModuleAddressZEVM for bankAddr is appropriate and consistent with the new addressing scheme.

To improve clarity and maintainability, consider adding a comment explaining the significance of this address:

spender, bankAddr := r.EVMAddress(), fungibletypes.ModuleAddressZEVM // bankAddr represents the new bank module address in ZEVM

Line range hint 1-210: Summary of changes: Consistent update to bank module addressing

The modifications in this file consistently update the bank contract address from bank.ContractAddress to fungibletypes.ModuleAddressZEVM. This change appears to be part of a larger architectural update in the system.

Key points:

  1. All approval and balance check operations now use the new module address.
  2. The changes maintain consistency across both ZRC20 and non-ZRC20 token tests.
  3. The updates improve the alignment between the test suite and the actual implementation of the bank module.

To further enhance the test suite:

  1. Consider adding comments explaining the significance of the address change.
  2. Refactor repeated balance checks into a helper function to reduce code duplication.
  3. Ensure that similar changes are applied consistently across other relevant test files in the project.
precompiles/bank/method_test.go (2)

138-138: Approve the improved error message.

The updated error message provides more specific information about the allowance issue, which is beneficial for debugging. To further enhance clarity, consider including the expected allowance value in the error message as well.

Consider updating the error message to include both the expected and actual allowance:

require.Contains(t, err.Error(), fmt.Sprintf("invalid allowance, expected: %d, got: 0", expectedAllowance))

This change would provide even more context for debugging purposes.


147-173: Approve the new test case for zero token deposit.

The addition of this test case improves the overall test coverage by checking the behavior when attempting to deposit 0 tokens. This is a valuable edge case to verify.

To enhance the test's robustness, consider adding an assertion to verify the state remains unchanged after the failed deposit attempt. For example:

// Verify the balance remains unchanged
balanceBefore := ts.fungibleKeeper.GetZRC20Balance(ts.ctx, ts.zrc20Address, caller)
// ... (existing test code) ...
balanceAfter := ts.fungibleKeeper.GetZRC20Balance(ts.ctx, ts.zrc20Address, caller)
require.Equal(t, balanceBefore, balanceAfter, "Balance should remain unchanged after failed deposit")

This additional check ensures that the failed deposit doesn't unintentionally modify the token balance.

changelog.md (2)

Line range hint 76-143: Breaking changes in version v12.0.0

This version introduces several breaking changes, including:

  1. Moving TSS and chain validation queries from 'crosschain' to 'observer' module
  2. Unifying the observer set for all chains
  3. Merging observer params and core params into chain params
  4. Changes to the TSS address query for Bitcoin

These changes are significant and will require updates to any external systems or scripts that interact with these endpoints. Ensure that all documentation has been updated to reflect these changes and that a migration guide is provided for users.

Action items:

  1. Update all documentation referencing the old endpoints
  2. Provide a migration guide for users
  3. Update any internal scripts or systems that use the old endpoints
  4. Ensure that all new endpoints are thoroughly tested for correctness and performance

Line range hint 195-196: Test improvements

The addition of unit tests for ballot voting is a positive step towards improving test coverage. Consider expanding test coverage to other critical areas of the system.

Consider adding more comprehensive end-to-end tests to cover complex scenarios involving multiple modules.

x/fungible/keeper/zrc20_check_balance.go (1)

16-17: Remove unnecessary comma in function comment for clarity

The comment on the CheckFungibleZRC20Balance function contains an unnecessary comma that disrupts the sentence flow. For better readability, consider removing it.

Apply this diff to correct the comment:

-// CheckFungibleZRC20Balance checks if the balance of ZRC20 tokens,
-// is equal or greater than the provided amount.
+// CheckFungibleZRC20Balance checks if the balance of ZRC20 tokens
+// is equal to or greater than the provided amount.
x/fungible/keeper/zrc20_check_allowance.go (2)

53-55: Enhance VM error handling with additional context

Returning the raw res.VmError may not provide sufficient insight. Wrapping it with additional context can aid in debugging.

Apply this diff to improve the error message:

-		return fmt.Errorf("%s", res.VmError)
+		return fmt.Errorf("EVM call to 'allowance' method failed: %s", res.VmError)
🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 53-54: x/fungible/keeper/zrc20_check_allowance.go#L53-L54
Added lines #L53 - L54 were not covered by tests


67-69: Improve error message for insufficient allowance

The current error message may not clearly indicate the nature of the issue. Providing a more detailed message helps callers understand why the operation failed.

Apply this diff to enhance the error message:

-		return fmt.Errorf("invalid allowance, got: %s", allowance.String())
+		return fmt.Errorf("insufficient allowance: required %s, but got %s", amount.String(), allowanceValue.String())
🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 67-68: x/fungible/keeper/zrc20_check_allowance.go#L67-L68
Added lines #L67 - L68 were not covered by tests

x/fungible/keeper/zrc20_unlock_token.go (1)

60-62: Provide more context in VM error messages

Returning the raw VM error may not provide sufficient context for troubleshooting. Consider adding additional information to the error message to aid in debugging.

Apply this diff to enhance the error message:

     if res.VmError != "" {
-        return fmt.Errorf("%s", res.VmError)
+        return fmt.Errorf("EVM execution error: %s", res.VmError)
     }
precompiles/bank/method_deposit.go (1)

105-105: Consistency in Error Context Naming

The When field in the error is set to "LockZRC20InBank". For consistency and clarity, consider renaming it to "LockZRC20", matching the function name. This uniformity aids in debugging and maintaining clear error logs.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 1a32f05 and 8ef6a05.

📒 Files selected for processing (12)
  • changelog.md (1 hunks)
  • e2e/e2etests/test_precompiles_bank.go (8 hunks)
  • e2e/e2etests/test_precompiles_bank_through_contract.go (8 hunks)
  • precompiles/bank/method_deposit.go (3 hunks)
  • precompiles/bank/method_test.go (12 hunks)
  • precompiles/bank/method_withdraw.go (4 hunks)
  • x/fungible/keeper/zrc20_check_allowance.go (1 hunks)
  • x/fungible/keeper/zrc20_check_balance.go (1 hunks)
  • x/fungible/keeper/zrc20_check_token_validity.go (1 hunks)
  • x/fungible/keeper/zrc20_lock_token.go (1 hunks)
  • x/fungible/keeper/zrc20_unlock_token.go (1 hunks)
  • x/fungible/types/keys.go (1 hunks)
🧰 Additional context used
📓 Path-based instructions (11)
e2e/e2etests/test_precompiles_bank.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

e2e/e2etests/test_precompiles_bank_through_contract.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

precompiles/bank/method_deposit.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

precompiles/bank/method_test.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

precompiles/bank/method_withdraw.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

x/fungible/keeper/zrc20_check_allowance.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

x/fungible/keeper/zrc20_check_balance.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

x/fungible/keeper/zrc20_check_token_validity.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

x/fungible/keeper/zrc20_lock_token.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

x/fungible/keeper/zrc20_unlock_token.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

x/fungible/types/keys.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

🪛 GitHub Check: codecov/patch
precompiles/bank/method_withdraw.go

[warning] 62-62: precompiles/bank/method_withdraw.go#L62
Added line #L62 was not covered by tests


[warning] 113-113: precompiles/bank/method_withdraw.go#L113
Added line #L113 was not covered by tests


[warning] 120-120: precompiles/bank/method_withdraw.go#L120
Added line #L120 was not covered by tests

x/fungible/keeper/zrc20_check_allowance.go

[warning] 23-25: x/fungible/keeper/zrc20_check_allowance.go#L23-L25
Added lines #L23 - L25 were not covered by tests


[warning] 28-29: x/fungible/keeper/zrc20_check_allowance.go#L28-L29
Added lines #L28 - L29 were not covered by tests


[warning] 32-33: x/fungible/keeper/zrc20_check_allowance.go#L32-L33
Added lines #L32 - L33 were not covered by tests


[warning] 36-50: x/fungible/keeper/zrc20_check_allowance.go#L36-L50
Added lines #L36 - L50 were not covered by tests


[warning] 53-54: x/fungible/keeper/zrc20_check_allowance.go#L53-L54
Added lines #L53 - L54 were not covered by tests


[warning] 57-59: x/fungible/keeper/zrc20_check_allowance.go#L57-L59
Added lines #L57 - L59 were not covered by tests


[warning] 62-64: x/fungible/keeper/zrc20_check_allowance.go#L62-L64
Added lines #L62 - L64 were not covered by tests


[warning] 67-68: x/fungible/keeper/zrc20_check_allowance.go#L67-L68
Added lines #L67 - L68 were not covered by tests


[warning] 71-71: x/fungible/keeper/zrc20_check_allowance.go#L71
Added line #L71 was not covered by tests

x/fungible/keeper/zrc20_check_balance.go

[warning] 23-25: x/fungible/keeper/zrc20_check_balance.go#L23-L25
Added lines #L23 - L25 were not covered by tests


[warning] 28-29: x/fungible/keeper/zrc20_check_balance.go#L28-L29
Added lines #L28 - L29 were not covered by tests


[warning] 32-45: x/fungible/keeper/zrc20_check_balance.go#L32-L45
Added lines #L32 - L45 were not covered by tests


[warning] 48-49: x/fungible/keeper/zrc20_check_balance.go#L48-L49
Added lines #L48 - L49 were not covered by tests


[warning] 52-54: x/fungible/keeper/zrc20_check_balance.go#L52-L54
Added lines #L52 - L54 were not covered by tests


[warning] 57-59: x/fungible/keeper/zrc20_check_balance.go#L57-L59
Added lines #L57 - L59 were not covered by tests


[warning] 62-63: x/fungible/keeper/zrc20_check_balance.go#L62-L63
Added lines #L62 - L63 were not covered by tests


[warning] 66-66: x/fungible/keeper/zrc20_check_balance.go#L66
Added line #L66 was not covered by tests

x/fungible/keeper/zrc20_check_token_validity.go

[warning] 11-13: x/fungible/keeper/zrc20_check_token_validity.go#L11-L13
Added lines #L11 - L13 were not covered by tests


[warning] 16-18: x/fungible/keeper/zrc20_check_token_validity.go#L16-L18
Added lines #L16 - L18 were not covered by tests


[warning] 21-22: x/fungible/keeper/zrc20_check_token_validity.go#L21-L22
Added lines #L21 - L22 were not covered by tests


[warning] 25-25: x/fungible/keeper/zrc20_check_token_validity.go#L25
Added line #L25 was not covered by tests

x/fungible/keeper/zrc20_lock_token.go

[warning] 25-27: x/fungible/keeper/zrc20_lock_token.go#L25-L27
Added lines #L25 - L27 were not covered by tests


[warning] 30-31: x/fungible/keeper/zrc20_lock_token.go#L30-L31
Added lines #L30 - L31 were not covered by tests


[warning] 34-35: x/fungible/keeper/zrc20_lock_token.go#L34-L35
Added lines #L34 - L35 were not covered by tests


[warning] 38-39: x/fungible/keeper/zrc20_lock_token.go#L38-L39
Added lines #L38 - L39 were not covered by tests


[warning] 42-43: x/fungible/keeper/zrc20_lock_token.go#L42-L43
Added lines #L42 - L43 were not covered by tests


[warning] 46-60: x/fungible/keeper/zrc20_lock_token.go#L46-L60
Added lines #L46 - L60 were not covered by tests

🔇 Additional comments (33)
x/fungible/keeper/zrc20_check_token_validity.go (1)

10-26: 🛠️ Refactor suggestion

Enhance error handling and improve documentation

The IsValidZRC20 function is well-structured and performs the necessary checks. However, there are a few suggestions for improvement:

  1. Consider using custom error types instead of fmt.Errorf for better error handling and consistency across the codebase. This approach allows for more granular error checking by callers.

  2. Enhance the function documentation by including a code example demonstrating its usage. This will improve the overall package documentation and assist developers in understanding how to use the function correctly.

Here's an example of how you might implement these suggestions:

// ErrZRC20NotWhitelisted is returned when a ZRC20 token is not whitelisted
var ErrZRC20NotWhitelisted = errors.New("ZRC20 is not whitelisted")

// ErrZRC20Paused is returned when a ZRC20 token is paused
var ErrZRC20Paused = errors.New("ZRC20 is paused")

// IsValidZRC20 returns an error whenever a ZRC20 is not whitelisted or paused.
//
// Example usage:
//
//	zrc20Address := common.HexToAddress("0x1234...")
//	err := keeper.IsValidZRC20(ctx, zrc20Address)
//	if err != nil {
//		// Handle the error
//	}
func (k Keeper) IsValidZRC20(ctx sdk.Context, zrc20Address common.Address) error {
	if zrc20Address == zeroAddress {
		return fmt.Errorf("zrc20 address cannot be zero")
	}

	t, found := k.GetForeignCoins(ctx, zrc20Address.String())
	if !found {
		return fmt.Errorf("%w: %s", ErrZRC20NotWhitelisted, zrc20Address.String())
	}

	if t.Paused {
		return fmt.Errorf("%w: %s", ErrZRC20Paused, zrc20Address.String())
	}

	return nil
}

Additionally, it's crucial to ensure comprehensive test coverage for this function. Please add unit tests that cover all branches, including the zero address case, non-whitelisted case, paused case, and the success case. Here's a script to verify the current test coverage:

This script will help identify existing test cases and provide information about the current test coverage for the IsValidZRC20 function.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 11-13: x/fungible/keeper/zrc20_check_token_validity.go#L11-L13
Added lines #L11 - L13 were not covered by tests


[warning] 16-18: x/fungible/keeper/zrc20_check_token_validity.go#L16-L18
Added lines #L16 - L18 were not covered by tests


[warning] 21-22: x/fungible/keeper/zrc20_check_token_validity.go#L21-L22
Added lines #L21 - L22 were not covered by tests


[warning] 25-25: x/fungible/keeper/zrc20_check_token_validity.go#L25
Added line #L25 was not covered by tests

x/fungible/types/keys.go (2)

30-30: Formatting adjustment approved.

The reformatting of the ModuleAddress declaration aligns with Go's standard formatting practices, enhancing code consistency and readability.


Line range hint 1-35: Approval for removal of unused init() function.

The removal of the init() function, which contained only commented-out code, is commendable. This change improves code cleanliness and removes potential confusion for future developers.

e2e/e2etests/test_precompiles_bank_through_contract.go (3)

15-15: Import statement addition is appropriate.

The addition of the fungibletypes import is necessary and follows Go conventions for import organization.


72-72: Balance check modification is consistent.

The update to use fungibletypes.ModuleAddressZEVM is consistent with the previous change and maintains the logical flow of the test.


75-75: Allowance approval modification is appropriate.

The update to use fungibletypes.ModuleAddressZEVM for allowance approval is correct and consistent with the new approach for the bank precompile.

e2e/e2etests/test_precompiles_bank.go (3)

13-13: Import statement addition is appropriate.

The addition of the fungibletypes import is necessary and follows Go conventions.


63-63: Approval address update for 500 ERC20ZRC20 tokens is correct.

The change to use fungibletypes.ModuleAddressZEVM is appropriate and maintains consistency with the new addressing scheme.


76-76: Approval address update for 1000 ERC20ZRC20 tokens is correct.

The change to use fungibletypes.ModuleAddressZEVM is appropriate and maintains consistency with the new addressing scheme for the bank module.

precompiles/bank/method_test.go (6)

58-59: Consistent update of caller address.

This change is consistent with the previous modification of the caller address.


85-86: Consistent update of caller address.

This change is consistent with the previous modifications of the caller address.


Line range hint 119-133: Approve address update and deposit amount change.

The caller address update is consistent with previous changes. However, the deposit amount has been increased from 100 to 1000. Please ensure that this modification doesn't adversely affect the test case behavior or expected outcomes.

To verify the impact of the deposit amount change, please review the following:

  1. Check if there are any assertions or conditions in the test that depend on the specific deposit amount.
  2. Ensure that the increased amount doesn't overflow any limits or cause unexpected behavior in the contract methods being tested.

176-177: Consistent updates of caller address.

These changes are consistent with the previous modifications of the caller address from ModuleAddressEVM to ModuleAddressZEVM.

Also applies to: 197-197, 224-225, 278-279, 324-325, 403-404


572-575: Approve the update in the allowBank function.

The change from ModuleAddressEVM to ModuleAddressZEVM in the allowBank function is consistent with the previous modifications. This update ensures that the ZEVM module address is approved to spend tokens, aligning with the other changes in the file.

To ensure this change doesn't have unintended consequences, please run the following script:

#!/bin/bash
# Check for any remaining instances of ModuleAddressEVM in relation to token approval
rg --type go "ModuleAddressEVM.*approve"

# Check for the usage of ModuleAddressZEVM in relation to token approval
rg --type go "ModuleAddressZEVM.*approve"

This will help verify that all relevant token approval operations have been updated consistently.


31-32: Approve the caller address update.

The change from ModuleAddressEVM to ModuleAddressZEVM is consistent. However, it's crucial to ensure this modification is applied consistently across the entire codebase.

To verify the consistency of this change, please run the following script:

changelog.md (15)

20-21: New feature added: Fungible keeper ability to lock/unlock ZRC20 tokens

This new feature enhances the functionality of the fungible keeper. It's a significant addition that should be thoroughly tested to ensure it doesn't introduce any vulnerabilities or unexpected behavior in token management.


Line range hint 54-57: CI pipeline improvements

The fixes to the release pipelines and cleanup steps are important for maintaining a smooth and reliable release process. It's crucial to ensure that these changes have been thoroughly tested in a staging environment before being applied to the production release pipeline.


Line range hint 59-62: Chores and documentation updates

The updates to release instructions and the addition of an upgrade handler for version v12.1.0 are important for maintaining clear documentation and smooth upgrade processes. Ensure that the upgrade handler has been thoroughly tested with various upgrade scenarios.


Line range hint 187-193: Chores and minor updates

The chores and minor updates, such as renaming files and updating build configurations, contribute to better code organization and build processes. Ensure that these changes don't introduce any unexpected behavior in the build or runtime environments.


Line range hint 198-199: CI improvements

The removal of private runners and unused GitHub Action contributes to a cleaner and more maintainable CI setup. Ensure that all necessary CI processes are still in place and functioning correctly after these removals.


Line range hint 1-199: Overall assessment of the changelog

The changelog demonstrates significant development efforts across multiple versions, with a focus on enhancing functionality, reliability, and performance. Key points to note:

  1. Version v12.0.0 introduces several breaking changes, particularly in module organization and query endpoints. These changes will require careful migration planning for users.

  2. New features have been added consistently, including monitoring capabilities, dynamic gas pricing, and improved transaction handling.

  3. Numerous fixes address critical issues in various areas such as transaction processing, chain validation, and event handling.

  4. Refactoring efforts have improved code organization and maintainability.

  5. Test coverage has been expanded, although there's room for more comprehensive testing.

  6. CI/CD processes have been streamlined and improved.

Action items:

  1. Develop and publish a comprehensive migration guide for the breaking changes in v12.0.0.
  2. Conduct thorough testing of new features and fixes, especially under high load conditions and edge cases.
  3. Continue expanding test coverage, particularly for complex scenarios involving multiple modules.
  4. Monitor the effects of dynamic gas pricing in production environments.
  5. Update all documentation to reflect the latest changes, especially regarding new and modified endpoints.

Overall, the changelog reflects a project in active development with a strong focus on improvement and stability. The breaking changes, while potentially disruptive, seem to be in service of a more organized and maintainable codebase.


Line range hint 39-52: Multiple fixes and improvements in version v12.1.0

This version includes several important fixes and improvements:

  1. Avoiding voting on wrong ballots due to false blockNumber in EVM tx receipt
  2. Fixing chain params comparison logic
  3. Exempting system transactions from min gas price check and gas fee deduction
  4. Setting keygen status correctly
  5. Fixing zetaclient crash issues
  6. Skipping unsupported chain parameters

These changes address critical issues and improve the robustness of the system. However, it's important to ensure that these fixes don't introduce new edge cases or unexpected behavior.

To verify the impact of these changes, especially for EVM-related fixes, we can run the following script:

#!/bin/bash
# Description: Check for any remaining references to old EVM transaction handling

# Test: Search for old EVM transaction handling methods
rg --type go 'EVM.*Transaction' --glob '!changelog.md'

Line range hint 64-68: New features and support added

The addition of support for lower gas limits, improvements to inbound transaction observation, and the integration of authenticated calls are significant enhancements. These features should be thoroughly tested, especially in edge cases and under high load conditions.

To verify the implementation of these features, we can run the following script:

#!/bin/bash
# Description: Check for the implementation of new features

# Test: Search for lower gas limit implementation
rg 'lower.*gas.*limit' --type go

# Test: Search for inbound transaction observation improvements
rg 'inbound.*transaction.*observation' --type go

# Test: Search for authenticated calls integration
rg 'authenticated.*calls' --type go

Line range hint 70-74: Code refactoring and optimizations

The refactoring efforts, including the reorganization of zetaclient into subpackages and the addition of EVM fee calculation to TSS migration, are positive steps towards improving code organization and maintainability. However, ensure that these changes don't introduce any regressions or unexpected behavior.

To verify the impact of the refactoring, we can run the following script:

#!/bin/bash
# Description: Check for any remaining references to old package structure

# Test: Search for old package references
rg 'zetaclient/[^/]+/' --type go --glob '!zetaclient/'

Line range hint 154-169: Multiple fixes in v12.0.0

The fixes address various issues including UTXO handling, EVM chain outbound transaction processing, and event sanity checks. These improvements enhance the reliability and security of the system. However, ensure that these fixes have been thoroughly tested, especially in edge cases and under high load conditions.

To verify the impact of these fixes, we can run the following script:

#!/bin/bash
# Description: Check for any remaining references to old transaction handling methods

# Test: Search for old UTXO handling methods
rg 'UTXO' --type go --glob '!changelog.md'

# Test: Search for old EVM outbound transaction handling
rg 'EVM.*outbound.*transaction' --type go --glob '!changelog.md'

# Test: Search for event sanity checks
rg 'event.*sanity.*check' --type go

Line range hint 145-152: New features added in v12.0.0

The addition of monitoring capabilities, state variables for aborted zeta amounts, and new commands are positive enhancements. The enablement of dynamic gas prices on zetachain is a significant change that should be carefully monitored in production for any unexpected effects on transaction processing or user costs.

To verify the implementation of these features, we can run the following script:

#!/bin/bash
# Description: Check for the implementation of new features in v12.0.0

# Test: Search for monitoring implementation
rg 'grafana|prometheus|ethbalance' --type go

# Test: Search for aborted zeta amount tracking
rg 'aborted.*zeta.*amount' --type go

# Test: Search for dynamic gas price implementation
rg 'dynamic.*gas.*price' --type go

Line range hint 171-185: Refactoring and improvements in v12.0.0

The refactoring efforts, including the consolidation of node builds and updates to contract bytecode management, contribute to improved code organization and maintainability. The changes to queries for large data sets by adding pagination are particularly important for scalability.

To verify the impact of the refactoring and improvements, we can run the following script:

#!/bin/bash
# Description: Check for implementation of pagination and new query structures

# Test: Search for pagination implementation
rg 'pagination' --type go

# Test: Search for new query structures
rg 'grpc.*query|msg.*query' --type go

Line range hint 23-30: Multiple fixes in version v12.2.4

The fixes address several important issues:

  1. Ensuring external chain height always increases
  2. Buffering EIP1559 gas price increase
  3. Changing authorization for WhitelistERC20
  4. Handling pending outbound transaction hashes
  5. Scheduling bitcoin keysign with intervals
  6. Skipping Goerli BlobTxType transactions
  7. Handling Mumbai empty blocks
  8. Using estimated SegWit tx size for Bitcoin gas fee calculation
  9. Using chain param ConfirmationCount for bitcoin confirmation

These fixes appear to address critical issues and improve the overall stability and functionality of the system. However, it's important to ensure that these changes don't introduce new issues or regressions.

To verify the impact of these changes, especially for Bitcoin-related fixes, we can run the following script:


Line range hint 35-37: Modification to emission distribution

The change to use fixed block rewards for emission distribution is a significant alteration to the economic model of the system. This change should be carefully reviewed to ensure it aligns with the project's tokenomics goals and doesn't introduce any unintended consequences.

To verify the implementation of this change, we can run the following script:


Line range hint 32-33: Removal of standalone network and update to testing package

This change simplifies the testing setup and potentially improves test consistency. However, it's crucial to ensure that all existing tests have been updated to work with the new testing package and that test coverage hasn't been reduced.

To verify the impact of this change, we can run the following script:

✅ Verification successful

Removal of Standalone Network References Verified

All references to the standalone network have been successfully removed or updated. The testing setup remains simplified and consistent with the new testing package.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining references to standalone network

# Test: Search for standalone network references
rg 'standalone.*network' --glob '!changelog.md'

Length of output: 6062


Script:

#!/bin/bash
# Description: Thoroughly check for any remaining references to "standalone network" in the codebase

# Search for exact phrase "standalone network" with word boundaries
rg '\\bstandalone\\s+network\\b' --glob '!changelog.md'

# Search for variations like "standaloneNetwork" or "StandaloneNetwork"
rg '\\bstandaloneNetwork\\b' --glob '!changelog.md'
rg '\\bStandaloneNetwork\\b' --glob '!changelog.md'

# Search for imports or related terms that might reference standalone network components
rg 'import.*standalone' --glob '!changelog.md'
rg 'standalone.*import' --glob '!changelog.md'

Length of output: 263

x/fungible/keeper/zrc20_check_allowance.go (1)

36-48: Ensure correct EVM call parameters

Verify that the parameters passed to CallEVM are correct for invoking the allowance method. Specifically, ensure that the caller address fungibletypes.ModuleAddressZEVM is appropriate and that the flags for gas estimation and state transition (true, true) align with the intended read-only operation.

Would you like to confirm that CallEVM is correctly configured for this context?

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 36-50: x/fungible/keeper/zrc20_check_allowance.go#L36-L50
Added lines #L36 - L50 were not covered by tests

x/fungible/keeper/zrc20_unlock_token.go (1)

13-14: ⚠️ Potential issue

Define 'zeroAddress' to avoid undefined identifier

The variable zeroAddress is used in the address checks but is not defined within this context. This will result in a compilation error due to an undefined identifier.

Define zeroAddress as follows:

 package keeper

+import "github.com/ethereum/go-ethereum/common"
+
+var zeroAddress = common.Address{}
 
 const transfer = "transfer"

Alternatively, you can replace zeroAddress with common.Address{} directly in the checks.

Likely invalid or redundant comment.

precompiles/bank/method_deposit.go (1)

21-21: Clarification of Required Permissions

The updated comment correctly specifies that the caller must allow the Fungible ZEVM address to spend ZRC20 tokens on their behalf. This enhances clarity regarding the necessary permissions for the deposit process.

x/fungible/keeper/zrc20_check_balance.go Outdated Show resolved Hide resolved
x/fungible/keeper/zrc20_check_balance.go Outdated Show resolved Hide resolved
x/fungible/keeper/zrc20_check_allowance.go Outdated Show resolved Hide resolved
x/fungible/keeper/zrc20_check_allowance.go Outdated Show resolved Hide resolved
x/fungible/keeper/zrc20_check_allowance.go Outdated Show resolved Hide resolved
precompiles/bank/method_withdraw.go Show resolved Hide resolved
precompiles/bank/method_withdraw.go Outdated Show resolved Hide resolved
precompiles/bank/method_withdraw.go Outdated Show resolved Hide resolved
precompiles/bank/method_deposit.go Outdated Show resolved Hide resolved
precompiles/bank/method_deposit.go Outdated Show resolved Hide resolved
e2e/e2etests/test_precompiles_bank.go Outdated Show resolved Hide resolved
x/fungible/keeper/zrc20_lock_token.go Outdated Show resolved Hide resolved
x/fungible/keeper/zrc20_lock_token.go Outdated Show resolved Hide resolved
x/fungible/keeper/zrc20_lock_token.go Outdated Show resolved Hide resolved
x/fungible/keeper/zrc20_lock_token.go Outdated Show resolved Hide resolved
@fbac fbac requested a review from lumtis October 8, 2024 15:54
Copy link
Member

@lumtis lumtis left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we summarize the workflow in the PR description or somewhere?

From my understanding, what we discussed for deposit was:

  • approval to the bank module
  • bank module use transferFrom to fungible module
  • call lock function of fungible that lock the amount in its balance

e2e/e2etests/test_precompiles_bank.go Outdated Show resolved Hide resolved
x/fungible/keeper/zrc20_lock_token.go Outdated Show resolved Hide resolved
x/fungible/keeper/zrc20_cosmos_coins_mapping.go Outdated Show resolved Hide resolved
x/fungible/keeper/zrc20_cosmos_coins_mapping.go Outdated Show resolved Hide resolved
x/fungible/keeper/zrc20_cosmos_coins_mapping.go Outdated Show resolved Hide resolved
x/fungible/keeper/zrc20_cosmos_coins_mapping.go Outdated Show resolved Hide resolved
@fbac fbac marked this pull request as draft October 9, 2024 15:55
@fbac fbac requested a review from lumtis October 10, 2024 12:17
@zeta-chain zeta-chain deleted a comment from codecov bot Oct 10, 2024
@fbac fbac marked this pull request as ready for review October 10, 2024 12:18
@fbac fbac force-pushed the feat/add-lock-zrc20-function-fungible branch from 77b72e6 to ed0d764 Compare October 10, 2024 12:19
Copy link

codecov bot commented Oct 10, 2024

Codecov Report

Attention: Patch coverage is 67.48971% with 79 lines in your changes missing coverage. Please review.

Project coverage is 66.38%. Comparing base (250b90e) to head (900da58).
Report is 3 commits behind head on develop.

Files with missing lines Patch % Lines
x/fungible/keeper/zrc20_methods.go 70.00% 24 Missing and 24 partials ⚠️
x/fungible/keeper/zrc20_cosmos_coins_mapping.go 71.01% 10 Missing and 10 partials ⚠️
precompiles/bank/method_withdraw.go 0.00% 6 Missing and 5 partials ⚠️
Additional details and impacted files

Impacted file tree graph

@@             Coverage Diff             @@
##           develop    #2979      +/-   ##
===========================================
+ Coverage    66.25%   66.38%   +0.12%     
===========================================
  Files          406      408       +2     
  Lines        22772    22924     +152     
===========================================
+ Hits         15088    15217     +129     
- Misses        6907     6909       +2     
- Partials       777      798      +21     
Files with missing lines Coverage Δ
precompiles/bank/method_deposit.go 49.23% <100.00%> (+6.77%) ⬆️
precompiles/bank/method_withdraw.go 24.19% <0.00%> (-10.51%) ⬇️
x/fungible/keeper/zrc20_cosmos_coins_mapping.go 71.01% <71.01%> (ø)
x/fungible/keeper/zrc20_methods.go 70.00% <70.00%> (ø)

@fbac fbac force-pushed the feat/add-lock-zrc20-function-fungible branch from d7d858b to 81997c8 Compare October 11, 2024 08:10
Copy link
Member

@lumtis lumtis left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The overall flow looks good to me.

One remaining thing we should have I think is introducing a mapping ZRC20Address -> LockedAmount in the fungible module store.

This would allow a more precise tracking as anyone can send ZRC20 to the module that would be not "locked"

This would also allow introducing an invariant that check balance>=locked

This can be implemented in a furhter PR

#2991

x/fungible/keeper/zrc20_cosmos_coins_mapping.go Outdated Show resolved Hide resolved
x/fungible/keeper/zrc20_cosmos_coins_mapping.go Outdated Show resolved Hide resolved
x/fungible/keeper/zrc20_cosmos_coins_mapping.go Outdated Show resolved Hide resolved
x/fungible/types/keys.go Outdated Show resolved Hide resolved
x/fungible/keeper/zrc20_cosmos_coins_mapping.go Outdated Show resolved Hide resolved
x/fungible/keeper/zrc20_cosmos_coins_mapping.go Outdated Show resolved Hide resolved
x/fungible/keeper/zrc20_cosmos_coins_mapping.go Outdated Show resolved Hide resolved
x/fungible/keeper/zrc20_methods.go Show resolved Hide resolved
x/fungible/keeper/zrc20_methods.go Outdated Show resolved Hide resolved
@fbac fbac force-pushed the feat/add-lock-zrc20-function-fungible branch from 6adb5ec to 10dcfd6 Compare October 11, 2024 17:44
@fbac fbac requested review from lumtis, swift1337 and skosito October 11, 2024 17:45
x/fungible/types/keys.go Outdated Show resolved Hide resolved
@fbac fbac requested a review from kingpinXD October 16, 2024 14:12
@fbac fbac added this pull request to the merge queue Oct 17, 2024
Merged via the queue into develop with commit 72b517d Oct 17, 2024
32 checks passed
@fbac fbac deleted the feat/add-lock-zrc20-function-fungible branch October 17, 2024 14:36
@coderabbitai coderabbitai bot mentioned this pull request Oct 17, 2024
5 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants